package com.nintendo.frame;

import com.nintendo.entity.pojo.Dish;
import com.nintendo.entity.pojo.Desk;
import com.nintendo.entity.pojo.DetailCustomer;
import com.nintendo.entity.pojo.Order;
import com.nintendo.mapper.*;
import com.nintendo.utils.MyBatisUtils;
import org.apache.ibatis.session.SqlSession;

import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

public class DetailCustomerFrame extends JFrame {

    private JTextField customerNameField;
    private JComboBox<String> tableNumberComboBox;
    private JTextField numberOfPeopleField;
    private JList<String> dishList;
    private DefaultListModel<String> listModel;
    private JComboBox<String> dishNameComboBox;
    private JTextField dishQuantityField;
    private JButton addButton;
    private JButton deleteButton;
    private JButton saveButton;

    public DetailCustomerFrame() {
        setTitle("消费者点餐详情");
        setSize(600, 400);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setLocationRelativeTo(null);

        // 创建面板
        JPanel panel = new JPanel();
        panel.setLayout(new BorderLayout());

        // 上部面板：消费者名称、餐台和就餐人数
        JPanel topPanel = new JPanel();
        topPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
        topPanel.add(new JLabel("消费者名称:"));
        topPanel.add(customerNameField = new JTextField(15));
        topPanel.add(new JLabel("餐台:"));
        topPanel.add(tableNumberComboBox = new JComboBox<>(getTableNumbers()));
        topPanel.add(new JLabel("就餐人数:"));
        topPanel.add(numberOfPeopleField = new JTextField(5));

        panel.add(topPanel, BorderLayout.NORTH);

        // 中部面板：菜品列表
        listModel = new DefaultListModel<>();
        dishList = new JList<>(listModel);
        dishList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        dishList.addListSelectionListener(new ListSelectionListener() {
            @Override
            public void valueChanged(ListSelectionEvent e) {
                if (!e.getValueIsAdjusting()) {
                    int selectedIndex = dishList.getSelectedIndex();
                    if (selectedIndex != -1) {
                        String selectedItem = listModel.getElementAt(selectedIndex);
                        String[] parts = selectedItem.split(" - ");
                        dishNameComboBox.setSelectedItem(parts[0]);
                        dishQuantityField.setText(parts[1]);
                    }
                }
            }
        });

        JScrollPane scrollPane = new JScrollPane(dishList);
        panel.add(scrollPane, BorderLayout.CENTER);

        // 下部面板：输入框和按钮
        JPanel bottomPanel = new JPanel();
        bottomPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
        bottomPanel.add(new JLabel("菜品名称:"));
        bottomPanel.add(dishNameComboBox = new JComboBox<>(getDishNames()));
        bottomPanel.add(new JLabel("数量:"));
        bottomPanel.add(dishQuantityField = new JTextField(5));

        addButton = new JButton("添加");
        addButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                addDish();
            }
        });
        bottomPanel.add(addButton);

        deleteButton = new JButton("删除");
        deleteButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                deleteDish();
            }
        });
        bottomPanel.add(deleteButton);

        saveButton = new JButton("保存");
        saveButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                saveOrder();
            }
        });
        bottomPanel.add(saveButton);

        panel.add(bottomPanel, BorderLayout.SOUTH);

        add(panel);
    }

    private String[] getTableNumbers() {
        SqlSession sqlSession = MyBatisUtils.getSqlSession();
        try {
            DeskDao mapper = sqlSession.getMapper(DeskDao.class);
            List<Desk> desks = mapper.selectAll();
            String[] tableNumbers = new String[desks.size()];
            for (int i = 0; i < desks.size(); i++) {
                tableNumbers[i] = desks.get(i).getNo();
            }
            return tableNumbers;
        } finally {
            sqlSession.close();
        }
    }

    private String[] getDishNames() {
        SqlSession sqlSession = MyBatisUtils.getSqlSession();
        try {
            DishDao mapper = sqlSession.getMapper(DishDao.class);
            List<Dish> dishes = mapper.selectAll();
            String[] dishNames = new String[dishes.size()];
            for (int i = 0; i < dishes.size(); i++) {
                dishNames[i] = dishes.get(i).getName();
            }
            return dishNames;
        } finally {
            sqlSession.close();
        }
    }

    private void addDish() {
        String dishName = (String) dishNameComboBox.getSelectedItem();
        String dishQuantity = dishQuantityField.getText().trim();
        if (dishName != null && !dishQuantity.isEmpty()) {
            String item = dishName + " - " + dishQuantity;
            listModel.addElement(item);
            dishQuantityField.setText("");

            // 添加到数据库
            SqlSession sqlSession = MyBatisUtils.getSqlSession();
            try {
                DetailCustomerDao detailCustomerDao = sqlSession.getMapper(DetailCustomerDao.class);
                String customerName = customerNameField.getText().trim();
                String tableNumber = (String) tableNumberComboBox.getSelectedItem();
                String numberOfPeople = numberOfPeopleField.getText().trim();
                int quantity = Integer.parseInt(dishQuantity);
                DetailCustomer order = new DetailCustomer();
                order.setUsername(customerName);
                order.setDeskName(tableNumber);
                order.setNumber(Integer.parseInt(numberOfPeople));
                order.setDishName(dishName);
                order.setDishCount(quantity);
                // 根据菜品名称查询价格
                SqlSession dishSession = MyBatisUtils.getSqlSession();
                DishDao dishMapper = dishSession.getMapper(DishDao.class);
                Double dishPrice = dishMapper.findByDishName(dishName);
                order.setTotalMoney(dishPrice * quantity);
                detailCustomerDao.insert(order);
                sqlSession.commit();

            } catch (Exception e) {
                sqlSession.rollback();
                JOptionPane.showMessageDialog(this, "添加菜品失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
            } finally {
                sqlSession.close();
            }
        }
    }

    private void deleteDish() {
        int selectedIndex = dishList.getSelectedIndex();
        if (selectedIndex != -1) {
            String selectedItem = listModel.getElementAt(selectedIndex);
            String[] parts = selectedItem.split(" - ");
            String dishName = parts[0];
            int quantity = Integer.parseInt(parts[1]);

            listModel.remove(selectedIndex);

            // 从数据库删除
            SqlSession sqlSession = MyBatisUtils.getSqlSession();
            try {
                OrderDao orderDao = sqlSession.getMapper(OrderDao.class);
                String customerName = customerNameField.getText().trim();
                String tableNumber = (String) tableNumberComboBox.getSelectedItem();
                orderDao.deleteOrder(customerName, tableNumber, dishName, quantity);
                sqlSession.commit();
            } catch (Exception e) {
                sqlSession.rollback();
                JOptionPane.showMessageDialog(this, "删除菜品失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
            } finally {
                sqlSession.close();
            }
        }
    }

    private void saveOrder() {
        String customerName = customerNameField.getText().trim();
        String tableNumber = (String) tableNumberComboBox.getSelectedItem();
        String numberOfPeople = numberOfPeopleField.getText().trim();

        if (customerName.isEmpty() || tableNumber == null || tableNumber.isEmpty() || numberOfPeople.isEmpty()) {
            JOptionPane.showMessageDialog(this, "请填写所有必填项", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        SqlSession sqlSession = MyBatisUtils.getSqlSession();
        try {
            /**
             *  id int primary key ,
             *     order_no varchar(20),
             *     desk_id int ,
             *     create_time date ,
             *     money double ,
             *     customerId int ,
             *     status varchar(4) ,
             *     number int
             */
            Order orderDetail = new Order();
            // 根据deskName 查询deskId
            DeskDao deskDao = sqlSession.getMapper(DeskDao.class);
//            Integer deskId = deskDao.selectByDeskName(tableNumber);
            orderDetail.setOrderNo(String.valueOf((System.currentTimeMillis() / 1000)));
            orderDetail.setDeskId(Integer.valueOf(tableNumber));
            orderDetail.setStatus("未支付");
            orderDetail.setCreateTime(new Date());
            orderDetail.setNumber(Integer.parseInt(numberOfPeople));
            // 根据客户名称查询客户id
            CustomerDao customerDao = sqlSession.getMapper(CustomerDao.class);
            Integer customerId  =  customerDao.findByUserName(customerName);
            orderDetail.setCustomerid(customerId);
            // 根据客户名称查询订单总金额
            DetailCustomerDao detailCustomerDao = sqlSession.getMapper(DetailCustomerDao.class);
            Double totalMoney = detailCustomerDao.findTotalMoneyByCustomerName(customerName);
            orderDetail.setMoney(totalMoney);
            OrderDao orderMapper = sqlSession.getMapper(OrderDao.class);
            orderMapper.insert(orderDetail);
            sqlSession.commit();

            JOptionPane.showMessageDialog(this, "订单已保存", "成功", JOptionPane.INFORMATION_MESSAGE);
            // 保存订单删除数据库 点餐记录
            detailCustomerDao.deleteByCustormerName(customerName);
            sqlSession.commit();
            dispose(); // 关闭当前页面
        } catch (Exception e) {
            sqlSession.rollback();
            e.printStackTrace();
//            JOptionPane.showMessageDialog(this, "保存订单失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        } finally {
            sqlSession.close();
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new DetailCustomerFrame().setVisible(true);
            }
        });
    }
}
